class Common {

    /**
     * @param arg 需要转化的字符串dom
     * return dom
     * */
    protected parseDom(arg: string): ChildNode {
        const objE = document.createElement("div");
        objE.innerHTML = arg;
        return objE.firstChild!;
    };

    /**
     * @param func 需要包装的函数
     * @param delay 延迟时间，单位ms
     * @param immediate 是否默认执行一次(第一次不延迟)
     */
    protected debounced(func: Function, delay: number, immediate: boolean = false): Function {
        let timer: number | undefined
        return (...args: any) => {
            if (immediate) {
                func.apply(this, args) // 确保引用函数的指向正确，并且函数的参数也不变
                immediate = false
                return
            }
            clearTimeout(timer)
            timer = window.setTimeout(() => {
                func.apply(this, args)
            }, delay)
        }
    }

    /**
     * @param func 需要包装的函数
     * @param delay 延迟时间，单位ms
     * @param immediate 是否默认执行一次(第一次不延迟)
     */
    protected throttle(func: Function, delay: number, immediate: boolean = false): Function {
        let flag = true
        let timer: number | undefined
        return (...args: any) => {
            if (immediate) {
                func.apply(this, args)
                immediate = false
                return
            }
            if (!flag) {
                return
            }
            flag = false
            timer = window.setTimeout(() => {
                func.apply(this, args)
                flag = true
            }, delay)
        }
    }
}

export default Common